import React, { FC, useState } from 'react'
import { Form, Button, Divider, Select, message } from 'antd'
import SuccessModal from '~/components/submit-successfully'
import ProductionVoucher from '~/components/production-voucher'
import TopHeader, { ListTitle } from '~/components/top-header'
import { useNavigate, useLocation } from 'react-router-dom'
import { queryWaitCastItems, handleApplyBorrow } from '~/api/borrow-property-api'
import { getUserInfo } from '~/mock/user/userinfo'
import { BorrowReasonMap } from '~/constants'

import { FooterAction } from './styled'
import PropertyList from './container/property-list'
import PropertySelect from './components/property-involved-select'

const { Option } = Select

const PropertyInvolved: FC = () => {
  const [form] = Form.useForm()
  const { state }: any = useLocation()
  const navigate = useNavigate()
  const [successVisible, setSuccessVisible] = useState(false)
  const [certificateVisible, setCertificateVisible] = useState(false)
  const [selectVisible, setSelectVisible] = useState(false)
  const [castItems, setCastItems] = useState([])
  const [selectedItems, setSelectedItems] = useState<any>([])
  const { validateFields } = form

  const { caseCompanyName, caseDepartmentName, caseName, caseNo } = state

  const handleGetCastItems = async (value?: any) => {
    const userInfo = getUserInfo()
    const { data } = await queryWaitCastItems({
      ...userInfo,
      ...value,
      caseName,
      caseNo
    })
    setCastItems(data)
  }

  const onClickBorrowCertficate = async (preview?: boolean) => {
    if (!selectedItems.length) {
      return message.error('请选择涉案财物')
    }
    console.log('preview=>preview', preview)
    const { borrowReason } = await validateFields()
    console.log('selectedItems', selectedItems)
    const userInfo = getUserInfo()
    const { data } = await handleApplyBorrow({
      ...userInfo,
      borrowReason: borrowReason,
      caseNo,
      caseName,
      items: selectedItems.map((item: any) => {
        return {
          number: item.itemStock.borrowNumber || item.itemStock.currentNumber,
          serialNo: item.itemStock.serialNo,
          unitName: item.itemStock.unitName
        }
      }),
      preview: !!preview
    })
    console.log('preview=>preview11', preview)
    window.open(data.url)
    if (preview) return
    setSuccessVisible(true)
  }

  const headData = [
    {
      childen: [
        {
          label: '案件编号:',
          value: caseNo
        },
        { label: '案件名称:', value: caseName }
      ]
    },
    {
      childen: [
        { label: '办案单位:', value: caseCompanyName },
        { label: '办案部门:', value: caseDepartmentName }
      ]
    }
  ]

  return (
    <div>
      <TopHeader headData={headData} />
      <ListTitle />
      <Divider />
      <main style={{ marginTop: 21 }}>
        <PropertyList
          selectedItems={selectedItems}
          setSelectedItems={setSelectedItems}
          handleGetCastItems={handleGetCastItems}
          setSelectVisible={setSelectVisible}
          form={form}
        />

        <h3>借用信息</h3>
        <Divider />
        <Form validateTrigger="onBlur" form={form}>
          <Form.Item rules={[{ required: true, message: '请选择借用事由' }]} label="借用事由" name="borrowReason">
            <Select placeholder="请选择借用事由" style={{ width: 200 }}>
              {[...BorrowReasonMap].map(([key, value], index) => (
                <Option key={index} value={key}>
                  {value}
                </Option>
              ))}
              {/* <Option value="CHECK">检测</Option>
              <Option value="APPRAISAL">鉴定</Option>
              <Option value="RECOGNIZE">辨认</Option>
              <Option value="EVALUATION">估价</Option>
              <Option value="TEST">检验</Option>
              <Option value="PROPAGATE">宣传</Option>
              <Option value="OTHER">其他</Option> */}
            </Select>
          </Form.Item>
        </Form>
        <FooterAction>
          <div>
            <Button onClick={() => navigate(-1)}>返回</Button>
            <Button
              onClick={() => {
                // setExeTimeVisible(true)
                onClickBorrowCertficate(true)
              }}
              style={{ marginLeft: 8 }}
            >
              预览借用凭证
            </Button>
            <Button
              onClick={() => {
                onClickBorrowCertficate()
              }}
              style={{ marginLeft: 8 }}
              type="primary"
            >
              制作借用凭证
            </Button>
          </div>
        </FooterAction>
      </main>
      <SuccessModal visible={successVisible} />
      <PropertySelect
        setSelectedItems={setSelectedItems}
        castItems={castItems}
        setSelectVisible={setSelectVisible}
        visible={selectVisible}
        selectedItems={selectedItems}
        handleGetCastItems={handleGetCastItems}
      />
      <ProductionVoucher
        onOk={() => {
          setCertificateVisible(false)
        }}
        onCancel={() => {
          setCertificateVisible(false)
        }}
        visible={certificateVisible}
      />
    </div>
  )
}

export default PropertyInvolved
